<template>
  <div class="page">
    <!-- 控制面板 -->
    <div class="control-panel">
      <div class="title"><h3>LUCC转移分析与VPM</h3></div>
      <div class="addlayer">
        <el-button
          type="success"
          plain
          class="clear"
          @click="loadLanduseFeature"
          >加载土地转移图层</el-button
        >
      </div>
      <el-select
        class="elselect"
        v-model="selectedTransition"
        size="medium"
        placeholder="筛选土地利用转移类型"
        @change="filterByTransition"
      >
        <el-option
          v-for="item in transitionTypes"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <el-button type="success" plain class="clear" @click="clearFilter"
        >清除筛选</el-button
      >
      <el-divider class="divider"></el-divider>
      <!-- VPM -->
      <div class="vpm">
        <h3>
          <el-button
            id="titlebtn"
            class="el-icon-s-help"
            type="text"
            @click="centerDialogVisible = true"
            ><span>VPM模拟GPP</span>:</el-button
          >
        </h3>
        <div class="addvpmlayer">
          <el-button
            id="vpmbtn"
            type="success"
            size="medium"
            class="el-icon-map-location"
            plain
            @click="addVPMLayer"
            ><span>加载GPP</span></el-button
          >
        </div>
      </div>
      <el-dialog
        class="gjinfo"
        title="生态系统净初级生产力模型"
        :modal-append-to-body="false"
        :append-to-body="true"
        :visible.sync="centerDialogVisible"
        width="50%"
        center
      >
        <p>
          生态系统总初级生产力模型 VPM 是用于指导植被光合作用的模型，
          它基于遥感数据 (如MODIS数据) 和气象数据来模拟植被总体初步生产力
          (GPP)。
        </p>
        <p>
          GPP: 是指植物通过光合作用固定的总碳量, 是生态系统碳循环中的关键部分。
        </p>
        <p>
          基本原理: VPM模型使用植被指数 (如EVI和LSWI) 和环境条件 (如温度和提示)
          来指示光配合速度。 VPM的核心植被被光利用效率 (LUE) 与环境胁迫因子
          (如温度和水分) 相结合, 以提示GPP。
        </p>
        <img style="height:200px;margin-left:50px" src="../assets/vpm.png" alt="">
      </el-dialog>
    </div>
    <div class="selectfeature" v-if="selectedFeature">
      <h4>选中图斑信息</h4>
      <el-divider class="divider"></el-divider>
      <p>
        转移类型:
        {{ selectedFeature.attributes.type }}
      </p>
      <el-divider class="divider"></el-divider>
      <p>
        面积:
        {{ (selectedFeature.attributes.area_ha / 10000).toFixed(2) }} 公顷
      </p>
      <el-divider class="divider"></el-divider>
      <p>
        土地转移总面积:
        {{ (typesArea[selectedFeature.attributes.type] / 10000).toFixed(2) }}
        公顷
      </p>
      <el-divider class="divider"></el-divider>
    </div>
    <!-- 图表 -->
    <div v-if="chartVisiable" ref="bar_ref" class="chart"></div>
    <!-- 地图容器 -->
    <div class="map-container">
      <ArcgisMap ref="map"></ArcgisMap>
    </div>
  </div>
</template>
<script>
import ArcgisMap from "@/components/arcgisMap.vue";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer";
export default {
  name: "LUCCAnalysis",
  components: {
    ArcgisMap,
  },
  data() {
    return {
      vpmlayer: null,
      luccLayer: null, // LUCC转移矢量图层
      selectedTransition: null,
      transitionTypes: [], // 存储所有转移类型用于下拉框
      selectedFeature: null, // 存储当前选中的要素信息
      clickHandler: null,
      centerDialogVisible: false, //VPM介绍
      totalArea: null,
      chart: null,
      chartVisiable: false,
      typesArea: {},
    };
  },
  mounted() {
    // 确保地图组件初始化完成后再加载图层
    setTimeout(() => {
      this.loadLayers();
    }, 500);
  },
  methods: {
    loadLayers() {
      try {
        // 初始化地图点击事件
        this.initMapClickHandler();
      } catch (error) {
        console.error("图层加载失败:", error);
        this.$message.error("地图资源加载失败，请刷新页面重试");
      }
    },
    initMapClickHandler() {
      if (!this.$refs.map?.view) return;

      // 存储事件处理器引用
      this.clickHandler = (event) => {
        this.$refs.map.view
          .hitTest(event)
          .then((response) => {
            const graphic = response.results.find(
              (r) => r.graphic?.layer === this.luccLayer
            )?.graphic;

            this.selectedFeature = graphic || null;
          })
          .catch((err) => {
            console.error("地图点击事件处理失败:", err);
          });
      };
      this.$refs.map.view.on("click", this.clickHandler);
    },
    async loadLanduseFeature() {
      // 先移除旧图层
      // 移除现有影像图层
      if (this.vpmlayer) {
        this.$refs.map.mapremove(this.vpmlayer);
      }
      // 2. 加载LUCC转移矢量服务 (这是后端预处理好的关键数据！)
      this.luccLayer = new FeatureLayer({
        url: "https://tjh.geosceneenterprise41.cn/server/rest/services/Hosted/landuse_transition/FeatureServer",
        outFields: ["*"], // 必须包含转移类型和面积字段
        popupTemplate: {
          title: "土地利用转移信息",
          content: [
            {
              type: "fields",
              fieldInfos: [
                {
                  fieldName: "type",
                  label: "转移类型",
                },
                {
                  fieldName: "area_ha",
                  label: "面积(平方米)",
                },
              ],
            },
          ],
        },
      });
      this.$refs.map.map.add(this.luccLayer);
      this.chartVisiable = true;
      setTimeout(() => {
        this.getTransition();
        this.getTotalArea();
      }, 500);
    },
    getTransition() {
      this.luccLayer.when(() => {
        const query = this.luccLayer.createQuery();
        query.outStatistics = [
          {
            statisticType: "count",
            onStatisticField: "type",
            outStatisticFieldName: "count",
          },
        ];
        query.groupByFieldsForStatistics = ["type"];
        this.luccLayer.queryFeatures(query).then((result) => {
          this.transitionTypes = result.features.map((f) => f.attributes.type);
        });
      });
    },
    //VPM
    addVPMLayer() {
      // 先移除旧图层
      // 移除现有影像图层
      if (this.luccLayer) {
        this.$refs.map.map.remove(this.luccLayer);
      }
      this.vpmlayer = new MapImageLayer({
        url: "https://tjh.geosceneenterprise41.cn/server/rest/services/2024gpp/MapServer",
      });
      this.$refs.map.map.add(this.vpmlayer);
      this.chartVisiable = false;
    },

    filterByTransition(selectedType) {
      // 根据选择的转移类型设置图层过滤器
      this.luccLayer.definitionExpression = `type = '${selectedType}'`;
    },
    //计算总面积
    getTotalArea() {
      if (!this.luccLayer) {
        return;
      }
      this.luccLayer.when(() => {
        const query = this.luccLayer.createQuery();
        query.groupByFieldsForStatistics = ["type"];
        query.outStatistics = [
          {
            statisticType: "sum", // 统计类型：总和
            onStatisticField: "area_ha", // 要统计的字段
            outStatisticFieldName: "totalArea", // 统计结果的字段名
          },
        ];
        this.luccLayer.queryFeatures(query).then((result) => {
          const features = result.features || [];
          // 用对象存储结果，比多个变量更简洁
          const typeAreaMap = {};

          features.forEach((feature) => {
            const attrs = feature.attributes;
            if (attrs) {
              const type = attrs.type;
              const totalArea = Number(attrs.totalArea) || 0;
              typeAreaMap[type] = totalArea; // 直接从统计结果获取总和
            }
          });
          this.typesArea = typeAreaMap;
          console.log(this.typesArea);
          this.landuseChart();
        });
      });
    },
    clearFilter() {
      this.selectedFeature = null
      // 清除过滤器，显示所有转移类型
      this.luccLayer.definitionExpression = "";
      this.selectedTransition = null;
    },
    //图表
    landuseChart() {
      //拿到键和值
      const keys = Object.keys(this.typesArea);
      const values = Object.values(this.typesArea);

      //拿到变化的数据
      const landuseName = [
        keys[1],
        keys[2],
        keys[3],
        keys[5],
        keys[6],
        keys[8],
      ];
      const landuseValue = [
        values[1],
        values[2],
        values[3],
        values[5],
        values[6],
        values[8],
      ];
      //初始化图表
      this.chart = this.$echarts.init(this.$refs.bar_ref);
      const initOption = {
        title: {
          text: `土地利用变化统计`,
          left: "center",
          top: "2%",
          textStyle: {
            fontSize: 16,
            color: "#fff",
          },
        },
        //高亮显示
        tooltip: {
          //触发条件，鼠标移入坐标轴
          trigger: "axis",
          //高亮类型
          axisPointer: {
            //线条
            type: "shadow",
            z: 0,
            lineStyle: {
              type: "solid",
              color: "#2D3443",
            },
          },
          backgroundColor: "rgba(16,12,42,0.9)",
          textStyle: {
            color: "#fff",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: true,
            data: landuseName,
          },
        ],
        yAxis: {
            type: "value",
            name:"平方米"
          },
        series: [
          {
            name: "npp",
            type: "bar",
            barWidth: "50%",
            data: landuseValue,
            itemStyle: {
              //柱状图圆角
              borderRadius: [10, 10, 0, 0],
            },
            label: {
              //数值标签
              show: true,
              position: "top",
              fontSize: 16,
              textStyle: {
                color: "#fff",
              },
            },
          },
        ],
      };
      this.chart.setOption(initOption);
    },
    cleanupResources() {
      // 移除事件监听
      // 移除并销毁图层
      if (this.$refs.map?.map) {
        if (this.luccLayer) {
          this.$refs.map.map.remove(this.luccLayer);
          this.luccLayer.destroy();
        }
      }
      // 销毁地图视图
      if (this.$refs.map?.view) {
        this.$refs.map.view.destroy();
      }
      //销毁图表
      if (this.chart) {
        this.chart.dispose();
      }
      // 清空状态
      this.luccLayer = null;
      this.selectedFeature = null;
      this.clickHandler = null;
      this.chart = null;
    },
  },
  beforeDestroy() {
    this.cleanupResources();
  },
};
</script>
<style scoped>
.page {
  position: relative;
  font-family: "华文楷体";
}
.control-panel {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 10;
  height: 40%;
  width: 20%;
  background: rgba(0, 0, 0, 0.5);
  padding: 5px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
.title {
  margin-bottom: 10px;
}
.addlayer {
  margin-bottom: 10px;
  margin-left: 30px;
}
.control-panel h3 {
  font-size: 20px;
  line-height: 30px;
  color: #16d229;
  text-align: center;
}
.clear {
  margin-left: 10px;
  border: 2px;
}

.divider {
  margin: 10px 0;
}

.elselect {
  width: 56%;
}
.selectfeature {
  position: absolute;
  top: 15px;
  left: 22%;
  padding: 5px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
}
.selectfeature h4 {
  font-size: 18px;
  line-height: 18px;
  text-align: center;
  color: aliceblue;
}
.selectfeature p {
  font-size: 16px;
  color: aliceblue;
}
.addvpmlayer {
  font-family: "华文楷体";
}
#titlebtn span {
  font-family: "华文楷体";
  font-size: 20px;
  font-weight: 600;
  color: #16d229;
}
.addvpmlayer #vpmbtn {
  margin-left: 70px;
}
.addvpmlayer span {
  font-family: "华文楷体";
}
.gjinfo p {
  font-size: 20px;
  line-height: 30px;
  font-family: "华文楷体";
}
.chart {
  position: absolute;
  bottom: 5px;
  right: 5px;
  height: 50%;
  width: 28%;
  border: 1px solid rgba(25, 186, 139, 0.17);
  background: rgba(0, 0, 0, 0.2);
  padding: 0 0.1875rem 0;
  margin-bottom: 0.1875rem;
  z-index: 10;
}
.map-container {
  height: 100%;
  width: 100%;
}
</style>